﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DTO;
using System.Data.SqlClient;

namespace DataAccess_Layer
{
    public static class Category_DAC
    {
        private static DataClasses_RetailerDataContext db = DataAccessHelper.DB;

        public static List<CategoryDTO> getAll()
        {
            List<CategoryDTO> cats = null;

            DataAccessHelper helper = null;
            SqlDataReader rdr = null;
            try
            {
                helper = new DataAccessHelper();
                
                rdr = helper.excuteSP("SP_Get_All_Category");

                if (rdr.HasRows)
                {
                    cats = new List<CategoryDTO>();
                    while (rdr.Read())
                    {
                        CategoryDTO cat = createCategory(ref rdr);
                        cats.Add(cat);
                    }
                }
            }
            finally
            {
                helper.close();
                rdr.Close();
            }

            return cats;
        }
        private static CategoryDTO createCategory(ref SqlDataReader rdr)
        {
            CategoryDTO cat = new CategoryDTO();
            cat.ID = (int)rdr["ID"];
            cat.Name = (string)rdr["Name"];            
            return cat;
        }

        public static List<Category> getAllLQ()
        {
            List<Category> cats = new List<Category>();

            foreach (var cat in db.Categories.Select(cat => cat))
            {
                cats.Add(cat);
            }

            return cats;
        }

        public static void insert(Category cat)
        {
            db.Categories.InsertOnSubmit(cat);
            DataAccessHelper.Save();
        }

        public static void delete(List<long> deletedIDs)
        {
            foreach (long deletedID in deletedIDs)
            {
                Category nccgh = DataAccessHelper.DB.Categories.Where(ncc => ncc.ID == deletedID).Select(ncc => ncc).First();
                DataAccessHelper.DB.Categories.DeleteOnSubmit(nccgh);
            }

            DataAccessHelper.Save();
        }

        public static void update(Category nCC_GiangHang)
        {
            Category nccgh = DataAccessHelper.DB.Categories.Where(ncc => ncc.ID == nCC_GiangHang.ID).Select(ncc => ncc).First();
            nccgh.ID = nCC_GiangHang.ID;
            nccgh.Name = nCC_GiangHang.Name;
            nccgh.MaChungLoaiSP = nCC_GiangHang.MaChungLoaiSP;
            nccgh.Hinh = nCC_GiangHang.Hinh;
            nccgh.DaXoa = nCC_GiangHang.DaXoa;
            DataAccessHelper.Save();
        }

        public static object layHet()
        {
            return DataAccessHelper.DB.Categories.Select(cat => new { cat.ID, cat.Hinh, cat.Name, cat.MaChungLoaiSP, TenCLSP = cat.ChungLoaiSP.Ten, cat.DaXoa });
        }
    }
}
